<template>
<div class="goods">
    <swiper class="swiper" indicator-dots="true" autoplay="true" interval="5000" duration="1000" style="height:400px">
        <block v-for="(item, index) in goods.thumb" :index="index" :key="key">
            <swiper-item>
                <image :src="item.imgUrl" class="slide-image" mode="aspectFill" bindload="imageLoad" />
            </swiper-item>
        </block>
    </swiper>
    <van-row>
        <van-col span="24">
            <div class="goods-price">￥ {{ goods.formatPrice }}</div>
        </van-col>
        <van-col span="24">
            <div class="goods-title">{{ goods.name }}</div>
        </van-col>
        <van-col span="24">
            <div class="goods-desc">{{ goods.descript }}</div>
        </van-col>

    </van-row>
    <van-row>
        <div class="goods-express">
            <van-col span="8">运费：免运费</van-col>
            <van-col span="8">剩余：{{ goods.stock }}</van-col>
            <van-col span="8">收藏：{{goods.likeNum}}</van-col>
        </div>
    </van-row>
    <van-row>
        <van-col span="24">
            <div style="padding:0">
                <wxParse :content="goods.detail" />
            </div>

        </van-col>
    </van-row>

    <van-goods-action>
        <van-goods-action-icon icon="home-o" text="主页" @click="toHome" />
        <div v-if="goods.favorite">
            <van-goods-action-icon icon="like"  text="喜欢" @click="unLike(goods.id)" />
        </div>
        <div v-else>
            <van-goods-action-icon icon="like-o" color="EE6363" text="喜欢" @click="like(goods.id)" />
        </div>
        <van-goods-action-icon icon="cart-o" text="购物车" @click.stop="goToCart" />
        <van-goods-action-button text="立即购买" @click="openAddDialog" />
    </van-goods-action>
    <van-popup :show="showDialog" position="bottom" custom-style="height: 50%;min-height:25rem;" closeable round @close="closeDialog">
        <div class="sel-goods" style="padding:1.1rem;">
            <van-row type="flex" align="bottom" justify="center" gutter="20">
                <van-col :span="10">
                    <van-image width="120" height="120" class="goods_item_image" :src="goods.imgUrl" alt="商品图片" radius="15" show-error="true" />
                </van-col>
                <van-col :span="12">
                    <div class="van-sku-header__goods-info">
                        <div class="van-sku__goods-price">
                            <span class="van-sku__price-symbol">￥</span>
                            <span class="van-sku__price-num">{{skuData.price}}</span>
                        </div>
                        <div class="van-sku-header-item">
                            <span class="van-sku__stock">剩余 <span class="van-sku__stock-num">{{skuData.stockNum}}</span>个</span>
                        </div>
                        <div class="van-sku-header-item">{{attrText}}</div>
                    </div>
                </van-col>
            </van-row>
            <van-row>
                <block v-for="(treeNode, index) in sku.tree" :index="index" :key="key">
                    <div class="item-attr-title">{{treeNode.k}}</div>
                    <van-tag v-for="(treeV,index2) in treeNode.v" :index="index2" :key="key2" color="#f2826a" :plain="treeV.plain" size="medium" style="margin:2px 10px 2px 0;" @click="chooseAttr(treeV,treeNode)">
                        {{treeV.name}}
                    </van-tag>
                </block>
            </van-row>

            <div class="buy-count">
                <div>
                    购买数量
                </div>
                <van-stepper v-model="skuData.selectedNum" theme="round" max="10" @change="onChange" />
            </div>
        </div>
        <van-goods-action>
            <van-goods-action-button text="加入购物车" type="warning" @click="addCart" />
            <van-goods-action-button text="立即购买" @click="buy" />
        </van-goods-action>

    </van-popup>
</div>
</template>

<script>
import utils from '@/utils/index.js'
import store from '@/utils/store.js'

import wxParse from 'mpvue-wxparse'

export default {
    components: {
        wxParse
    },
    data() {
        return {
            temp: 1,
            skuSel: {},
            likeIcon: "like-o",
            goods: {
                thumb: []
            },
            sku: [],
            imgheights: [],
            showDialog: false,
            chooseAttrText: {},
            plainTest: false,
            enoughStock: true,
            skuData: {
                idGoods: '',
                stockNum: '',
                selectedNum: 1,
                price: '',
                idSku: '',
                selAttrKey: {}
            },
            skuDataList: []
        }
    },
    computed: {
        attrText() {
            if (!this.sku.none_sku) {
                let ret = '请选择：'
                for (let key in this.chooseAttrText) {
                    ret += this.chooseAttrText[key] + ' '
                }
                return ret
            }
            return ''
        }
    },
    methods: {
        onChange(e) {
            this.skuData.selectedNum = e.mp.detail
            if (this.skuData.selectedNum > this.skuData.stockNum) {
                wx.showToast({
                    title: '库存不足，请重新选择！', //提示的内容,
                    icon: 'error', //图标,
                    duration: 2000, //延迟时间,
                    mask: true, //显示透明蒙层，防止触摸穿透,
                    success: res => {
                        this.enoughStock = false;
                    }
                });
            } else {
                this.enoughStock = true;
            }
        },
        getGoods(id) {
            this.$API.get('/goods/' + id).then(res => {
                //初始化SPU
                let goods = res.data.goods
                this.sku = res.data.sku
                let chooseAttrText = {}
                for (let i = 0; i < this.sku.tree.length; i++) {
                    chooseAttrText[this.sku.tree[i]['k_s']] = this.sku.tree[i].k
                }
                this.chooseAttrText = chooseAttrText
                goods.thumb = []
                const gallery = goods.gallery.split(',')
                for (const index in gallery) {
                    goods.thumb.push({
                        imgUrl: utils.fileMgrUrl + gallery[index]
                    })
                }
                goods.formatPrice = utils.formatPrice(goods.price);
                goods.imgUrl = utils.fileMgrUrl + goods.pic
                this.goods = goods
                //初始化SKU
                for (let index = 0; index < this.sku.list.length; index++) {
                    var targetSku = this.sku.list[index];
                    let skuInfo = {
                        idGoods: '',
                        stockNum: '',
                        selectedNum: 1,
                        price: '',
                        idSku: '',
                        selAttrKey: {}
                    };
                    skuInfo.idGoods = this.goods.id
                    skuInfo.stockNum = targetSku.stock_num + ""
                    skuInfo.price = targetSku.price
                    skuInfo.idSku = targetSku.id
                    for (let j = 0; j < this.sku.tree.length; j++) {
                        let curAttr = this.sku.tree[j];
                        skuInfo.selAttrKey[curAttr.k_s] = targetSku[curAttr.k_s]
                        for (let m = 0; m < curAttr.v.length; m++) {
                            if (curAttr.v[m].id + "" == targetSku[curAttr.k_s] + "") {
                                skuInfo.selAttrKey[this.sku.tree[j].k_s + "_name"] = curAttr.v[m].name;
                            }
                        }
                    }
                    this.skuDataList[index] = skuInfo;
                    if (index == 0) {
                        this.skuData = skuInfo;
                    }
                }
            })
        },
        formatPrice(price) {
            return utils.formatPrice(price)
        },
        toHome() {
            const url = '/pages/index/index'
            wx.switchTab({
                url
            })
        },
        like(goodsId) {
            this.$API.post("/user/favorite/add/" + goodsId).then((res) => {
                if (res.code == 20000) {
                    wx.showToast({
                        title: "添加喜欢",
                        icon: "success",
                        duration: 2000,
                    });
                    this.getGoods(goodsId);
                } else {
                    wx.showToast({
                        title: "添加失败，请稍后再试",
                        icon: "error",
                        duration: 2000,
                    });
                }
            });
        },
        unLike() {
            this.$API.post("/user/favorite/dislike/" + goodsId).then((res) => {
                if (res.code == 20000) {
                    wx.showToast({
                        title: "取消喜欢",
                        icon: "success",
                        duration: 2000,
                    });
                    this.getGoods();
                    this.likeIcon = "like"
                } else {
                    wx.showToast({
                        title: "取消失败，请稍后再试",
                        icon: "error",
                        duration: 2000,
                    });
                }
            });
        },
        goToCart() {
            wx.switchTab({
                url: '/pages/cart/index'
            })
        },
        openAddDialog() {
            this.showDialog = true
        },
        prepareSkuData() {
            if (this.sku.none_sku) {
                wx.showToast({
                    title: '所先选择商品不存在，请联系管理员',
                    icon: 'none'
                })
            }
            let finalValid = false;
            for (let m = 0; m < this.skuDataList.length; m++) {
                let skuItem = this.skuDataList[m];
                let isValid = true;
                for (let i = 0; i < this.sku.tree.length; i++) {
                    if (this.chooseAttrText[this.sku.tree[i]['k_s']] != skuItem.selAttrKey[this.sku.tree[i]['k_s'] + "_name"]) {
                        isValid = false;
                    }
                }
                if (isValid) {
                    this.skuData.idGoods = this.goods.id
                    this.skuData.stockNum = skuItem.stockNum + ""
                    this.skuData.price = skuItem.price
                    this.skuData.idSku = skuItem.idSku
                    finalValid = true;
                    break;
                }
            }
            if (!finalValid) {
                wx.showToast({
                    title: '当前商品规格暂时无货，请重新选择',
                    icon: 'none'
                })
                return false;
            }
            return true;

        },
        addCart() {
            if (!this.prepareSkuData()) {
                return
            }
            let skuData = this.skuData
            this.$API.post('user/cart/add', {
                idGoods: this.goods.id,
                idSku: this.sku.none_sku ? '' : skuData.idSku,
                count: skuData.selectedNum
            }).then(res => {
                wx.showToast({
                    title: '已经加入到购物车',
                    icon: 'success'
                })
                this.showDialog = false
            })
        },
        closeDialog(e) {
            this.showDialog = false
        },
        buy() {
            if (!this.enoughStock) {
                wx.showToast({
                    title: '库存不足请重新选择库存！', //提示的内容,
                    icon: 'error', //图标,
                    duration: 2000, //延迟时间,
                    mask: true, //显示透明蒙层，防止触摸穿透,
                });
                return;
            }
            if (!this.prepareSkuData()) {
                return;
            }
            let skuData = this.skuData
            this.$API.post('user/cart/add', {
                idGoods: this.goods.id,
                idSku: this.sku.none_sku ? '' : this.skuData.idSku,
                count: this.skuData.selectedNum
            }).then(res => {
                wx.switchTab({
                    url: '/pages/cart/index'
                })
            })
        },

        chooseAttr(treeV, treeNode) {
            this.plainTest = !this.plainTest
            let sku = this.sku
            this.skuData.selAttrKey[treeNode.k_s] = treeV.id
            for (let i = 0; i < sku.tree.length; i++) {
                if (sku.tree[i]['k_s'] === treeNode['k_s']) {
                    let skuSel = this.skuSel[treeNode['k_s']]
                    if (!skuSel) {
                        this.skuSel[treeNode['k_s']] = {}
                    }
                    // 第一个for循环将之前选中的取消掉
                    for (let j = 0; j < sku.tree[i].v.length; j++) {
                        if (skuSel) {
                            let skuSelIdKeyIndex = skuSel['idKeyIndex']
                            let skuSelIdValIndex = skuSel['idValIndex']
                            if (skuSelIdKeyIndex > -1 && skuSelIdValIndex > -1) {
                                if (skuSelIdKeyIndex === i && skuSelIdValIndex === j) {
                                    sku.tree[skuSelIdKeyIndex].v[skuSelIdValIndex].plain = !sku.tree[skuSelIdKeyIndex].v[skuSelIdValIndex].plain
                                }
                            }
                        }
                    }
                    // 第二个循环获取当前选中的标签标记选中
                    for (let j = 0; j < sku.tree[i].v.length; j++) {
                        if (sku.tree[i].v[j].id === treeV.id) {
                            this.chooseAttrText[sku.tree[i]['k_s']] = sku.tree[i].v[j].name
                            sku.tree[i].v[j].plain = !sku.tree[i].v[j].plain
                            this.skuSel[treeNode['k_s']]['idKeyIndex'] = i
                            this.skuSel[treeNode['k_s']]['idValIndex'] = j
                        }
                    }
                }
            }
            // 必须使用以下方式更新数组，使用数组的方法或者=赋值不会触发视图更新
            this.sku.tree = [...sku.tree]
        }
    },
    onLoad(options) {
        let id = options.id
        console.log('id:', id)
        this.skuSel = {}
        this.sku = {}
        this.showDialog = false
        this.skuData.selAttrKey = []
        this.getGoods(id)
    }
}
</script>

<style scoped>
.swiper image {
    width: 100%;
    height: 400px;
}

.goods {
    padding: 10px;
}

.goods-desc {
    font-size: 12px;
    color: #999999;
    letter-spacing: 0;
    line-height: 18px;
    margin: 6px 0;
}

.goods-detail {
    width: 100%;
    padding: 15px;
    font-size: 14px;
}

.goods_item_image {
    padding: 1px;
}

.van-image__img {
    border: 1px solid #FF6347;
}

.goods_item_price {
    font-size: 25px;
    color: #FF0000;
}

.goods_item_info {
    font-size: 15px;
    color: #363636;
}

.goods_item_stock {
    font-size: 15px;
    color: #363636;
}

.goods-title {
    margin-top: 10px;
    font-size: 16px;
}

.goods-price {
    color: #FF0000;
    font-size: 25px;
}

.goods-express {
    color: #2F4F4F;
    margin: 10px 0;
    font-size: 12px;
}

.buy-count {
    margin-top: 15px;
    font-size: 15px;
    font-weight: bold;
}

.van-sku-header__goods-info {
    display: -webkit-box;
    display: -webkit-flex;
    display: flex;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -webkit-flex-direction: column;
    flex-direction: column;
    -webkit-box-pack: end;
    -webkit-justify-content: flex-end;
    justify-content: flex-end;
    padding: 12px 20px 12px 0;
}

.van-sku__goods-price {
    margin-left: -2px;
    color: #ee0a24;
}

.van-sku__price-symbol {
    font-size: 16px;
    vertical-align: bottom;
}

.van-sku__price-num {
    font-weight: 500;
    font-size: 22px;
    vertical-align: bottom;
    word-wrap: break-word;
}

.van-sku-header-item {
    margin-top: 8px;
    color: #969799;
    font-size: 12px;
    line-height: 16px;
}

.van-sku__stock {
    display: inline-block;
    margin-right: 8px;
    color: #969799;
    font-size: 12px;
}

.van-sku__stock {
    display: inline-block;
    margin-right: 8px;
    color: #969799;
    font-size: 12px;
}

.item-attr-title {
    color: #363636;
    font-size: 15px;
    font-weight: bold;
    margin: 12px 0 5px 0;
}

.container {
    padding: 0
}
</style>
